package com.b511.swpu.cementbackend.service.impl;

import com.b511.swpu.cementbackend.dto.input.SysCompanyInputDto;
import com.b511.swpu.cementbackend.entity.MetaDict;
import com.b511.swpu.cementbackend.entity.SysCompany;
import com.b511.swpu.cementbackend.repository.SysCompanyRepository;
import com.b511.swpu.cementbackend.service.SysCompanyService;
import com.b511.swpu.cementbackend.util.CodeUtil;
import com.b511.swpu.cementbackend.util.R;
import com.b511.swpu.cementbackend.util.TreeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysSysCompanyServiceImpl implements SysCompanyService {

    private final SysCompanyRepository companyRepository;
    private final CodeUtil codeUtil;

    private TreeUtil treeUtil = new TreeUtil();

    public SysSysCompanyServiceImpl(SysCompanyRepository companyRepository, CodeUtil codeUtil) {
        this.companyRepository = companyRepository;
        this.codeUtil = codeUtil;

    }

    @Override
    public R getSysCompany() {
        List<SysCompany> all = companyRepository.findByIsEnableTrue();
        return R.ok().putData(treeUtil.getTree(all));
    }

    @Override
    @Transactional
    public R addSysCompany(SysCompanyInputDto sysCompanyInputDto) {
        String maxCode = companyRepository.findMaxLevel1Code(SysCompany.DICT_LEVEL_LENGTH);
        String nextCode = null == maxCode ? codeUtil.initCode(SysCompany.DICT_LEVEL_LENGTH) : codeUtil.next(maxCode);
        return addDictProcess(nextCode, sysCompanyInputDto);
    }

    @Override
    @Transactional
    public R addChildSysCompany(String parentCode, SysCompanyInputDto sysCompanyInputDto) {
        String maxLevel2Code = companyRepository.findMaxLevel2Code(parentCode.length(), parentCode);
        String nextCode = maxLevel2Code.equals(parentCode) ? parentCode + codeUtil.initCode(MetaDict.DICT_LEVEL_LENGTH) : codeUtil.next(maxLevel2Code);
        return addDictProcess(nextCode, sysCompanyInputDto);
    }

    private R addDictProcess(String nextCode, SysCompanyInputDto sysCompanyInputDto) {
        SysCompany sysCompany = new SysCompany();
        sysCompany.setCode(nextCode);
        BeanUtils.copyProperties(sysCompanyInputDto, sysCompany);
        System.out.println(sysCompany.getId()+","+sysCompany.getCode()+","+sysCompany.getLabel()+","+sysCompany.getIsEnable());
        companyRepository.save(sysCompany);
        return R.ok();
    }

    @Override
    @Transactional
    public R deleteSysCompany(String code) {
        companyRepository.deleteByCode(code);
        return R.ok();
    }

    @Override
    @Transactional
    public R updateSysCompanyName(String code, SysCompanyInputDto sysCompanyInputDto) {
        companyRepository.updateCompanyName(code, sysCompanyInputDto.getLabel());
        return R.ok();
    }
}
